package com.link510.aitools.activity.airobot.core;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.google.common.base.Strings;
import com.link510.aitools.R;
import com.link510.aitools.core.helper.UriHelper;
import com.link510.aitools.core.helper.ValidateHelper;
import com.link510.aitools.core.listen.CWMListener;
import com.link510.aitools.core.message.MessageInfo;
import com.link510.aitools.framework.activity.BaseAcitivity;
import com.link510.aitools.services.Airobots;
import com.link510.aitools.services.QiniuUtils;
import com.link510.aitools.services.CustomWaitDialogUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class RobotCoreUpgradeActivity extends BaseAcitivity {

    private String path = "";

    private boolean isLocal = false;

    @BindView(R.id.upgrade_edit_text)
    EditText upgradeEditText;

    private CustomWaitDialogUtils customWaitDialogUtils;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_robot_core_upgrade);
        setTitle("固件更新");
        customWaitDialogUtils = new CustomWaitDialogUtils(this.mContext);
        path = getString(R.string.upgrade_url);
        upgradeEditText.setText(path);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.robot_core_upgrade_topmenu, menu);
        return super.onCreateOptionsMenu(menu);
    }


    // 菜单的监听方法
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.select_upgrade_item) {
            ToastUtils.showShort("选择本地固件");

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            //intent.setType(“image/*”);//选择图片
            //intent.setType(“audio/*”); //选择音频
            //intent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
            //intent.setType("application/x-zip-compressed");//同时选择视频和图片
            intent.setType("*/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, 1);

        }

        return true;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();

            if (uri == null) {
                return;
            }

            if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
                this.path = uri.getPath();
                this.upgradeEditText.setText(path);
                this.isLocal = true;
                ToastUtils.showShort(path + "11111");
                return;
            }


            this.path = UriHelper.getInstance().getPath(mContext, uri);
            this.upgradeEditText.setText(path);

            Toast.makeText(this, path, Toast.LENGTH_SHORT).show();
            //String filepath = getPath(uri);
        } else {
            this.path = getString(R.string.upgrade_url);
            this.upgradeEditText.setText(path);
            this.isLocal = false;
        }
    }


    @OnClick(R.id.upgrade_button)
    public void upgradeButtonClick() {


        if (Strings.isNullOrEmpty(this.path)) {
            ToastUtils.showShort("固件路径不能为空");
            return;
        }


        if (isLocal) {

            File file = new File(this.path);
            if (!file.exists()) {
                ToastUtils.showShort("固件包不存在或无读取权限");
                return;
            }

            customWaitDialogUtils.show("文件上传中..");
            QiniuUtils.getInstance().upload(file, new CWMListener<String>() {
                @Override
                public void onSuccess(String message, String httpUrl) {
                    upgradeSend(httpUrl);
                }

                @Override
                public void onError(int code, String message) {
                    customWaitDialogUtils.close();
                }
            });

        } else {
            this.path = upgradeEditText.getText().toString().trim();
            upgradeSend(this.path);
        }


    }

    /**
     * 更新包发送
     *
     * @param httpUrl httpUrl
     */
    public void upgradeSend(String httpUrl) {

        if (!ValidateHelper.getInstance().isZipUrl(httpUrl)) {
            ToastUtils.showShort("固件路径错误");
            customWaitDialogUtils.close();
            return;
        }

        Airobots.getInstance().coreUpgradeSend(this.deviceSN, httpUrl, new CWMListener<MessageInfo<String>>() {

            /**
             * 解析成功
             * <p>
             * * @param message 消息
             *
             * @param message message
             * @param s       实体消息
             */
            @Override
            public void onSuccess(String message, MessageInfo<String> s) {
                customWaitDialogUtils.close();
                ToastUtils.showShort("固件下发成功");
            }


            /**
             * 返回错误解析
             *
             * @param code    错误状态码
             *                * @param message 消息
             * @param message
             */
            @Override
            public void onError(int code, String message) {
                customWaitDialogUtils.close();
                ToastUtils.showShort("固件下发失败");
            }
        });
    }

}